package com.mdd.front.service.impl;

import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.GoodsShare;
import com.mdd.common.entity.RefundRecord;
import com.mdd.common.entity.ShareDetail;
import com.mdd.common.entity.goods.Goods;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.user.User;
import com.mdd.common.enums.RefundEnum;
import com.mdd.common.mapper.GoodsShareMapper;
import com.mdd.common.mapper.ShareDetailMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.UrlUtils;
import com.mdd.front.service.ShareService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.vo.goods.GoodsListsVo;
import com.mdd.front.vo.share.SharingInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 分享实现类
 */
@Service
public class ShareServiceImpl implements ShareService {
    @Resource
    GoodsShareMapper goodsShareMapper;

    @Resource
    ShareDetailMapper shareDetailMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    OrderMapper orderMapper;



    @Override
    public PageResult<SharingInfoVo> Sharing(PageValidate pageValidate, Integer userId, Integer isBuy, String queryTime) {
        Integer page = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<ShareDetail> mpjQueryWrapper = new MPJQueryWrapper<ShareDetail>();
        mpjQueryWrapper.leftJoin("?_goods_share gs ON t.share_user_id=gs.user_id".replace("?_", GlobalConfig.tablePrefix));
        mpjQueryWrapper.leftJoin("?_user u ON u.id = t.share_user_id".replace("?_", GlobalConfig.tablePrefix));
        mpjQueryWrapper.leftJoin("?_goods g ON t.goods_id=g.id".replace("?_", GlobalConfig.tablePrefix));
        mpjQueryWrapper.select("t.id,u.id as user_id,u.avatar,u.username,u.nickname,u.mobile,t.goods_id,g.`name` as goods_name,t.is_buy,t.brokerage");
        if(!StringUtils.isEmpty(queryTime)){
            mpjQueryWrapper.like("DATE_FORMAT(FROM_UNIXTIME(t.create_time),'%Y-%m-%d')",queryTime);
        }
        if(isBuy!=2){
            mpjQueryWrapper.eq("t.is_buy",isBuy);
        }
        Page<ShareDetail> iPage = shareDetailMapper.selectPage(new Page<>(page, limit), mpjQueryWrapper);
        //分享次数
        QueryWrapper<GoodsShare> queryWrapper = new QueryWrapper<GoodsShare>();
        queryWrapper.eq("user_id",userId);
        Long goodsCount = goodsShareMapper.selectCount(queryWrapper);
        Integer shareNumber = Math.toIntExact(goodsCount);

        //购买人数
		QueryWrapper<ShareDetail> queryWrapperCount = new QueryWrapper<ShareDetail>();
		queryWrapperCount.eq("is_buy",1);
		queryWrapperCount.eq("share_user_id", userId);
        if(!StringUtils.isEmpty(queryTime)){
            mpjQueryWrapper.like("DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d')",queryTime);
        }
        Long buyersNumber = shareDetailMapper.selectCount(queryWrapperCount);

        //金额
//        QueryWrapper<ShareDetail> queryWrapper2 = new QueryWrapper<ShareDetail>();
        BigDecimal totalAmount = shareDetailMapper.sum("brokerage", queryWrapperCount);


        List<SharingInfoVo> list = new ArrayList<>();
        HashMap<String, Object> resultMap = new HashMap<>();
        for (ShareDetail record : iPage.getRecords()) {
            SharingInfoVo sharingInfoVo = new SharingInfoVo();
            BeanUtils.copyProperties(record, sharingInfoVo);
            sharingInfoVo.setAvatar(UrlUtils.toAbsoluteUrl(record.getAvatar()));
            Long buNum=0L;
            if(record.getGoodsId()>0&& record.getUserId()!=null){
                //查询当前商品购买数量
                MPJQueryWrapper<Order> queryWrapperByNum = new MPJQueryWrapper<Order>();
                queryWrapperByNum.leftJoin("?_order_goods og ON t.id=og.order_id".replace("?_", GlobalConfig.tablePrefix));
                queryWrapperByNum.eq("og.user_id",record.getUserId());
                queryWrapperByNum.eq("og.goods_id",record.getGoodsId());
                queryWrapperByNum.eq("t.is_bind",1);
                queryWrapperByNum.select("t.id");
                buNum = orderMapper.selectCount(queryWrapperByNum);
            }
            sharingInfoVo.setBuyNumber(buNum);
            list.add(sharingInfoVo);
        }
        resultMap.put("shareNumber",shareNumber);
        resultMap.put("buyersNumber",buyersNumber);
        resultMap.put("totalMoney",totalAmount);

        return PageResult.iPageHandle(iPage.getTotal(),iPage.getCurrent(),iPage.getSize(),list,resultMap);
    }

    @Override
    @Transactional
    public AjaxResult share(Integer userId,String code,String username,Integer goodsId) {
        if(StringUtils.isNotNull(code)){
            return AjaxResult.failed("记录失败,邀请码为空！");
        }
        //查询绑定人
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = userMapper.selectOne(userQueryWrapper);

        //通过邀请码查询邀请人
        QueryWrapper<User> shareUserQueryWrapper=new QueryWrapper<>();
        shareUserQueryWrapper.eq("code",code);
        User shareUser = userMapper.selectOne(shareUserQueryWrapper);
        if (shareUser==null||user==null){
            return AjaxResult.failed("记录失败,邀请码错误！");
        }
        //判断是否创建了
//        QueryWrapper<GoodsShare> wrapper=new QueryWrapper<>();
//        wrapper.eq("user_id",shareUser.getId());
//        GoodsShare goodsShare1 = goodsShareMapper.selectOne(wrapper);
//        if(goodsShare1==null){//未创建记录
            //记录次数
            GoodsShare goodsShare = new GoodsShare();
            goodsShare.setUserId(shareUser.getId());
//            goodsShare.setShareNumber(1);
            goodsShare.setCreateTime(System.currentTimeMillis() / 1000);
            goodsShare.setUpdateTime(System.currentTimeMillis() / 1000);
            goodsShareMapper.insert(goodsShare);
            //添加详细
            ShareDetail shareDetail=new ShareDetail();
            shareDetail.setShareUserId(shareUser.getId());
            shareDetail.setUserId(user.getId());
            shareDetail.setGoodsId(goodsId);
            int insert1 = shareDetailMapper.insert(shareDetail);
            return insert1>0?AjaxResult.success("记录成功！"): AjaxResult.failed("记录失败！");
//        }else {
//            Integer shareNumber = goodsShare1.getShareNumber();
//            shareNumber++;
//            GoodsShare goodsShare = new GoodsShare();
//            goodsShare.setId(goodsShare1.getId());
//            goodsShare.setShareNumber(shareNumber);
//            goodsShare.setUpdateTime(System.currentTimeMillis() / 1000);
//            int updateGoodsShare = goodsShareMapper.updateById(goodsShare);
//            return updateGoodsShare>0?AjaxResult.success("记录成功！"): AjaxResult.failed("记录失败！");
//        }

    }

    @Override
    public User isRegister(String username) {
        User model = userMapper.selectOne(new QueryWrapper<User>()
                .select("id,sn,username")
                .eq("username", username)
                .eq("is_delete", 0)
                .eq("is_close", 0)
                .last("limit 1"));

        return model;
    }
}
